import './index.scss'

import * as THREE from "three"
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";

const scene = new THREE.Scene()
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.01, 1000)
camera.position.set(1, 5, 8)
const renderer = new THREE.WebGLRenderer()
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)

// 地表格
const grid = new THREE.GridHelper(500, 100, 0xffffff, 0xffffff)
grid.material.opacity = 0.5
grid.material.depthWrite = false
grid.material.transparent = true
scene.add(grid)

// 地板
const geoFloor = new THREE.PlaneGeometry( 15, 15 );
const matFloor = new THREE.MeshPhongMaterial({color: 0xff0000});
matFloor.needsUpdate = true;
const mshFloor = new THREE.Mesh( geoFloor, matFloor );
mshFloor.rotation.x = - Math.PI / 2;
mshFloor.receiveShadow = true;
// mshFloor.castShadow = true;
const bgFloor = new THREE.PlaneGeometry(2, 1)
const bgmatFloor = new THREE.MeshPhongMaterial({color: 0xff0000});
const textureLoader = new THREE.TextureLoader();
scene.add( mshFloor );
textureLoader.loadAsync('./image/t_startroom_light.raw.jpg').then(texture => {
    bgmatFloor.map = texture;
    bgmatFloor.needsUpdate = true;
    const BGmshFloor = new THREE.Mesh( bgFloor, bgmatFloor );
    BGmshFloor.position.y = .47
    BGmshFloor.position.z = -.45
    BGmshFloor.receiveShadow = false;
    scene.add( BGmshFloor );
});
// 灯光
scene.add(new THREE.AmbientLight(0x444444))
const light = new THREE.DirectionalLight(0xffffff)
light.position.set(0, 20, 20)
light.castShadow = true
light.shadow.camera.top = 10
light.shadow.camera.bottom = -10
light.shadow.camera.left = -10
light.shadow.camera.right = 10
//告诉平行光需要开启阴影投射
light.castShadow = true
scene.add(light)

// 控制器
const control = new OrbitControls(camera, renderer.domElement)

// 辅助器
const axesHelper = new THREE.AxesHelper(5);
scene.add(axesHelper);

// 背景
scene.background = new THREE.Color(0xbbbbbb)

// 预设动画
const clock = new THREE.Clock()
let mixer: THREE.AnimationMixer | null = null;

// GLB加载器
const loader = new GLTFLoader();
loader.load('glb/Xbot.glb', function (gltf) {
    mixer = new THREE.AnimationMixer(gltf.scene)
    gltf.scene.scale.set(1, 1, 1);
    console.log(gltf);
    scene.add(gltf.scene);

    // const model = gltf.scene;
    console.log(gltf.animations);
    mixer.clipAction(gltf.animations[3]).play()
})

function animate() {
    requestAnimationFrame(animate)
    if (mixer) mixer.update(clock.getDelta())
    control.update()
    render();
}

function render() {
    renderer.render(scene, camera)
}

animate();
